<?php
/**
 * @file uploadfile.php
 * @author yuebin
 */
namespace haibao\www\business;

class UploadFile extends \haibao\www\business\Base{
	
	public static function saveUpload($file,$needSavePath = false){
		$storagePath = self::getUploadStoragePath($file['name']);
		$savePath = self::generateImage($storagePath, file_get_contents($file['tmp_name']));
		$data = array(
			'imageUrl' => $storagePath
		);
		
		if ($needSavePath){
			$data['savePath'] = $savePath;
		}
		
		return $data;
	}
	
	
	/**
	 * 获取要上传文件的存储路径
	 * @return string /upload/question/2014/1230/1419842617.9557.jpg
	 */
	public static function getUploadStoragePath($orgionName){
		
		$basePath = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::IMAGE_UPLOAD_BASE_PATH).date('Y').DIRECTORY_SEPARATOR.date('md').DIRECTORY_SEPARATOR.microtime(true);
		$extension = pathinfo($orgionName);
		$basePath .= '.' . strtolower($extension['extension']);
		return str_replace(array('/', '\\'), '/', $basePath);
	}
	
	/**
	 * 保存生图片
	 */
	private static function generateImage($path, $stream){
		$savePath = self::getSaveImagePath($path);
		self::createDir($savePath);
		file_put_contents($savePath, $stream);
		
		return $savePath;
	}
	
	/**
	 * 获取文件保存路径
	 */
	private static function getSaveImagePath($path){
		return \haibao\frame\Environment::path() . $path;
	}
	
	/**
	 * 创建文件保存路径
	 */
	private static function createDir($path){
		$path = pathinfo( $path );
		return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
	}
	
}

